﻿using EasyCore.DataValidation;
using IP2Region.Net.Abstractions;
using IP2Region.Net.XDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Shyjus.BrowserDetection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.EndpointAudits
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 终节点审认服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="action"></param>
        public static void AddEndpointAudits(this IServiceCollection services, Action<EndpointAuditOption> action = null)
        {
            EndpointAuditOption option = new EndpointAuditOption();
            if (action == null) {
                action = (options) => { };//默认的方法
            } 
            action.Invoke(option);
            services.Configure(action);//注册审计参数
            if (!option.EnableEndpointAudit) return; //不启用终节点审计时，
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpContextAccessor, HttpContextAccessor>()); //访问基本信息
            services.TryAdd(ServiceDescriptor.Scoped<IBrowserDetector, BrowserDetector>()); //获得浏览器相关信息
            services.TryAddSingleton<ISearcher>(new Searcher(CachePolicy.Content, Path.Combine(AppContext.BaseDirectory, "SearcherResource", "ip", "ip2region.xdb")));//ip相关信息
            services.AddScoped<IEndpointAuditHandler, EndpointAuditDefaultHandler>();
            if (option.EndpointAuditHandler != null) {
                services.Replace(new ServiceDescriptor(typeof(IEndpointAuditHandler), option.EndpointAuditHandler, ServiceLifetime.Scoped));
            }
            //配置MVC选项
            services.Configure<MvcOptions>(options => {
                options.Filters.Add<EndpointAuditFilter>(-1);  
            });  
        }

    }
}
